package com.example.siyun.service.impl.loginserviceimpl;

import com.example.siyun.mapper.loginmapper.UserMapper;
import com.example.siyun.mapper.usermapper.UserDeveMapper;
import com.example.siyun.pojo.BackofficeTable;
import com.example.siyun.pojo.Userr;
import com.example.siyun.pojo.UserList;
import com.example.siyun.service.ex.InsertException;
import com.example.siyun.service.ex.UserNotFoundException;
import com.example.siyun.service.ex.UsernameDuplicatedException;
import com.example.siyun.service.loginservice.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserDeveMapper userDeveMapper;

    @Override
    @Transactional
    public void reg(Userr userr, UserList userList) {
        String username1 = userr.getUsername();
        Userr result=userMapper.findByUserName(username1);
        if(result!=null){
            throw new UsernameDuplicatedException("用户名被占用");
        }
        String oldPassword= userr.getPassword();
        String salt= UUID.randomUUID().toString().toUpperCase();
        String md5Password=getMD5Password(oldPassword,salt);
        userr.setPassword(md5Password);
        userr.setSalt(salt);



        userr.setIsDelete(0);
        userr.setCreatedUser(userr.getUsername());
        Date date=new Date();
        userr.setCreatedTime(date);
        userr.setModifiedTime(date);
        Integer rows = userMapper.insert(userr);
        userDeveMapper.addUserList(userList);
        if(rows!=1){
            throw new InsertException("插入过程中产生了未知的错误");
        }
    }
    @Transactional
    @Override
    public Userr login(String username) {
        Userr result=userMapper.findByUserName(username);
        return result;
    }
    @Transactional
    @Override
    public Userr phonelogin(String phone) {
        Userr result=userMapper.findByPhone(phone);
        if(result==null){
            throw new UserNotFoundException("用户不存在");
        }

        if(result.getIsDelete()==1){
            throw new UserNotFoundException("用户不存在");
        }
        return result;
    }
    @Transactional
    @Override
    public BackofficeTable fingbackofficetale(String name,int isdel) {
        return userMapper.fingBackOfficeTale(name,isdel);
    }


    private String getMD5Password(String password,String salt){
        for (int i=0;i<3;i++){
            password=DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();
        }
        return password;
    }

}
